/* Start Header **************************************************************/
/*!
\file Collision.cpp
\author David Seah Seng Chong, sengchong.seah, 250004910
\par email: sengchong.seah@digipen.edu
\date 20 July 2011
\brief 

Copyright (C) 2011 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents
without the prior written consent of DigiPen Institute of
Technology is prohibited.
*/
/* End Header ****************************************************************/

#include "PreCompiledHeader.h"
#include "Collision.h"
#include "Timer.h"

	/**************************************************************************/
	/*!
	\brief
	Checks for collision between 2 moving bounding rectangles returns true 
	if collision

	\param aabb1
	bounding rectangle 1

	\param vel1
	velocity of bounding rectangle 1

	\param aabb2
	bounding rectangle 2

	\param vel2
	velocity of bounding rectangle 2

	\return
	bool 
	 */
	/**************************************************************************/
	bool CollisionIntersection_RectRect(const AABB &aabb1, const Vec2 &vel1, 
										const AABB &aabb2, const Vec2 &vel2)
	{
		//step 1 - Start
		AABB A, B; //assigning to variables more familiar for ease
		A = aabb1;
		B = aabb2;

		//new velocity Vb
		Vector2D Vb = Vector2D(vel2.x - vel1.x, vel2.y - vel1.y);

		Vector2D Df, Dl;
		//DFirst
		Df.x = A.min.x - B.max.x ;
		Df.y = A.min.y - B.max.y ;
		//DLast
		Dl.x = A.max.x - B.min.x ;
		Dl.y = A.max.y - B.min.y ;

		
		//init times
		float Tf = Df.x/(float)Timer::GetInstance()->GetDeltaTime();
		float Tl = Dl.x/(float)g_appTime;

		//step 1 - End

		//x axis collsion checks step 2 - Start
		if(Vb.x < 0)
		{
			//case 1
			if(A.min.x > B.max.x)
			{
				return 0;
			}

			//case 4
			if(A.max.x < B.min.x)
			{
				Tf = max(Df.x/Vb.x, Tf);
			}

			if(A.min.x < B.max.x)
			{
				Tl = min(Dl.x/Vb.x, Tl);
			}
		}
		else
		{
			//case 2
			if(A.min.x > B.max.x)
			{
				Tf = max( Df.x/Vb.x, Tf);
			}
			if(A.max.x > B.min.x)
			{
				Tl = min( Dl.x/Vb.x, Tl);
			}
			//case 3
			if(A.max.x < B.min.x)
			{
				return 0;
			}
		}

		//case 5
		if(Tf > Tl)
		{
			return 0;
		}
		//x axis collsion checks step 2 - End

		//y axis collsion checks step 2 - Start
		if (Vb.y < 0)
		{
			//case 1
			if(A.min.y > B.max.y)
			{
				return 0;
			}
			//case 4
			if(A.max.y < B.min.y)
			{
				Tf = max(Df.y/Vb.y, Tf);
			}
			if(A.min.y < B.max.y)
			{
				Tl = min(Dl.y/Vb.y, Tl);
			}
		}
		else
		{
			//case 2
			if(A.min.y > B.max.y)
			{
				Tf = max(Df.y/Vb.y, Tf);
			}
			if(A.max.y > B.min.y)
			{
				Tl = min(Dl.y/Vb.y, Tl);
			}

			//case 3
  			if(A.max.y < B.min.y)
			{
				return 0;
			}
		}
		
		//case 5
		if(Tf > Tl)
		{
			return 0;
		}
		//y axis collsion checks step 2 - End

		//step 4 rectangles intersect
		return 1;
	}
